package org.dragonnova.business.dao;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.dragonnova.business.model.Pager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate4.HibernateTemplate;

public class BaseDao {
	protected SessionFactory sessionFactory;
	protected HibernateTemplate hibernateTemplate;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public HibernateTemplate getHibernateTemplate() {
		if (hibernateTemplate == null)
			hibernateTemplate = new HibernateTemplate(sessionFactory);
		return hibernateTemplate;
	}

	/**
	 * 封装数据
	 */
	public Map<String, Object> packData(Object obj) {
		Map<String, Object> map = new HashMap<>();
		if (obj != null) {
			map.put("result", 0);
			map.put("data", obj);
			map.put("message", "查询成功！");
		} else {
			map.put("result", -1);
			map.put("message", "暂无数据！");
		}
		return map;
	}

	/**
	 * 封装数据
	 */
	public Map<String, Object> packData(Object obj, Pager page) {
		Map<String, Object> map = new HashMap<>();
		if (obj != null) {
			map.put("result", 0);
			map.put("data", obj);
			map.put("message", "查询成功！");
		} else {
			map.put("result", -1);
			map.put("message", "暂无数据！");
		}
		map.put("page", "page");
		return map;
	}

	/**
	 * saveOrUpdate
	 * 
	 * @param object
	 * @return
	 */
	public Object saveOrUpdateObj(Object object) throws Exception {
		Session session = sessionFactory.openSession();
		Transaction trans = session.beginTransaction();
		Object result = session.merge(object);
		trans.commit();
		session.close();
		return result;
	}

	/**
	 * 根据id查询
	 * 
	 * @param clazz
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public Object findById(Class clazz,Object id) throws Exception {
		Session session = sessionFactory.openSession();
		Object obj = session.get(clazz, (Serializable)id);
		session.close();
		return obj;
	}

	/**
	 * 根据id删除
	 * 
	 * @param clazz
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public void delById(Class clazz, Object id) throws Exception {
		 HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
		 hibernateTemplate.delete(findById(clazz, (Serializable) id));
	}

}
